package com.fang.web;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;


import com.fang.entity.User;
import com.fang.service.UserService;
import com.fang.utils.MailUtils;
import com.fang.utils.UUIDUtils;

public class UserServlet extends BaseServlet {
	//登录验证,记住用户名
	public void login(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		UserService service = new UserService();
		
		User loginuser = service.queryUser(username,password);
		if(loginuser==null){
			req.setAttribute("info", "用户名或密码错误");
			req.getRequestDispatcher("/login.jsp").forward(req, res);
		}else{
			req.getSession().setAttribute("loginuser", loginuser);
			//记住用户名复选框的状态
			String remember = req.getParameter("remember");
			if(remember!=null){
				String name = URLEncoder.encode(loginuser.getUsername(),"utf-8");
				Cookie cookie = new Cookie("username",name);
				cookie.setMaxAge(99999);
				cookie.setPath("/");
				res.addCookie(cookie);
			}else{
				
				//req.getSession().removeAttribute("loginuser");
				String name = URLEncoder.encode(loginuser.getUsername(),"utf-8");
				Cookie cookie = new Cookie("username",null);
				cookie.setMaxAge(0);
				cookie.setPath("/");
				res.addCookie(cookie);
			}
			res.sendRedirect(req.getContextPath()+"/index.jsp");
		}
	}
	
	
	// 注册验证
	public void register(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 验证码判断
		String code1 = req.getParameter("captcha");
		String code2 = (String) req.getSession().getAttribute("code");
		if ("".equals(code1) || code1 == null || !code1.equalsIgnoreCase(code2)) {
			req.setAttribute("info", "验证码错误！");
			req.getRequestDispatcher("register.jsp").forward(req, resp);
		} else {
			// 注册判断
			User user = new User();
			try {
				BeanUtils.populate(user, req.getParameterMap());
				UserService service = new UserService();
				int a = service.queryUser(user);
				if (a == 1) {// ok,跳到中间页面
					// 保存User到数据库
					String uuid = UUIDUtils.getUUID();
					user.setCode(uuid);
					service.addUser(user);
					// resp.sendRedirect(req.getContextPath()+"/login.jsp");

					// 获取注册用户的邮箱地址,发送到email
					String email = user.getEmail();
					// 获取本机ip地址
					/*InetAddress addr = InetAddress.getLocalHost();
					String ip = addr.getHostAddress();
					System.out.println("本机IP---" + ip);
					String url = "http://" + ip
							+ ":8080/estore3/user?method=active&code=" + uuid;
					String content = "<font color='red'>天狗商城链接：请点击链接激活</font>"
							+ "<a href='" + url + "'>" + url + "</a>";*/
					//MailUtils.sendMail(email, "新用户激活", content);

					// 跳转到中间提醒页面，链接到邮箱登录页面
					resp.sendRedirect(req.getContextPath() + "/active.jsp");
				} else if (a == 2) {// 重复用户名
					req.setAttribute("info", "用户名已存在");
					req.getRequestDispatcher("register.jsp").forward(req, resp);
				} else {
					req.setAttribute("info", "页面异常，再次尝试");
					req.getRequestDispatcher("register.jsp").forward(req, resp);
				}
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
				req.setAttribute("info", "注册异常，再次尝试");
				req.getRequestDispatcher("register.jsp").forward(req, resp);
			}
		}
	}

	// 邮件激活
	public void active(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		String code = req.getParameter("code");
		UserService service = new UserService();
		service.active(code);
		res.sendRedirect(req.getContextPath() + "/login.jsp");
	}

	// 用户名重复验证
	public void checkName(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		String username = req.getParameter("username");
		User user = new User();
		user.setUsername(username);
		UserService service = new UserService();
		int i = service.queryUser(user);
		if (i == 2) {
			res.getWriter().write("true");
			// req.getRequestDispatcher("register.jsp").forward(req, res);
		} else {
			res.getWriter().write("false");
			// req.getRequestDispatcher("register.jsp").forward(req, res);
		}
	}

	// 手机短信发送
	public void sendMessage(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		String telephone = req.getParameter("telephone");
		String mes = req.getParameter("mes");
		System.out.println(telephone + mes);
		if (mes.equals("duanxin")) {
			// 发送的手机号,短信验证
			String mobile = telephone;
			// 随机生成6位短信验证码0.15451248515452147854
			String smsCode = (Math.random() + "").substring(2, 8);
			// 设置您要发送的内容(内容必须符合：【签名】您的验证码是 + 4-6位数字，或和某模板匹配)
			String content = "【天狗商城】您的验证码是" + smsCode
					+ ",天狗商城1000元礼品派发中，先到先得！注册即送大礼！";
			// 将验证码保存到session中，后续需要校验
			req.getSession().setAttribute("smsCode", smsCode);
			res.getWriter().write("验证码"+smsCode);
			// 发短信调用示例
			// String result = SMSUtils.send(mobile, smsCode);
			// System.out.println(result);
			System.out.println(content);
		} else {
			// 语音验证
			// 发送的手机号,短信验证
			String mobile = telephone;
			// 随机生成6位短信验证码0.15451248515452147854
			String smsCode = (Math.random() + "").substring(2, 8);
			// 设置您要发送的内容(内容必须符合：【签名】您的验证码是 + 4-6位数字，或和某模板匹配)
			String content = "【天狗商城】您的验证码是" + smsCode;
			// 将验证码保存到session中，后续需要校验
			req.getSession().setAttribute("smsCode", smsCode);
			// 发短信调用示例
			// String result = SMSUtils.send(mobile, smsCode);
			// System.out.println(result);
			System.out.println(content);
		}
	}

	// 短信验证码验证
	public void phoneCode(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		String code1 = req.getParameter("phonecode");
		String code2 = (String) req.getSession().getAttribute("smsCode");
		if (code1 == null || "".equals(code1) || !code1.equals(code2)) {
			res.getWriter().write(false + "");
		} else {
			res.getWriter().write(true + "");
		}
	}

	// 图片验证码验证
	public void imgCode(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		String code1 = req.getParameter("imgcode");
		String code2 = (String) req.getSession().getAttribute("code");
		if (code1 == null || "".equals(code1) || !code1.equalsIgnoreCase(code2)) {
			res.getWriter().write(false + "");
		} else {
			res.getWriter().write(true + "");
		}
	}
}